from mmlib import *


class Language:
    def __init__(self, lang):
        self.package = {}
        self.default = 'en_us'
        self.langList = False
        self.lang = self.default
        self.loadDefaultLanguage()
        self.setLang(lang)

    def setText(self, key, value=''):
        return self.setTextToLangPackage(self.lang, key, value)

    def setTextToLangPackage(self, lang, key, value=''):
        lang = self.standardLangCode(lang)

        if lang not in self.package:
            self.package[lang] = dict()

        if isinstance(key, dict):
            self.package[lang] = dict(self.package[lang], **key)
        else:
            self.package[lang][key] = value

        return self

    def text(self, key, *params):
        text = ''
        params = list(params)

        if key in self.package[self.lang]:
            text = self.package[self.lang][key]

        text_argn = getTextArgn(text)
        empty_params = createEmptyListByLength(text_argn)
        params = mergeAry(empty_params, params)
        return text.format(*params)

    def setLang(self, lang):
        lang = self.standardLangCode(lang)
        lang = self.default if lang == '' else lang

        if self.loadLang(lang):
            self.lang = lang
            return True

        return False


    def standardLangCode(self, lang):
        return lang.strip().lower().replace('-', '_')

    def getDefaultPackage(self):
        return self.package[self.default]

    def loadLang(self, lang):
        lang = self.standardLangCode(lang)
        lang_file = os.path.join(g_script_dir, 'languages', lang + '.lang')
        lang_help_file = os.path.join(g_script_dir, 'languages', lang + '.help')

        if os.path.isfile(lang_file):
            lang_content = fileGetContent(lang_file).strip()

            self.setTextToLangPackage(lang, self.getDefaultPackage())
            self.setTextToLangPackage(lang, eval('{{{}}}'.format(lang_content)))

            if os.path.isfile(lang_help_file):
                lang_help_content = fileGetContent(lang_help_file)
                self.setTextToLangPackage(lang, 'help', lang_help_content)
            return True

        return False

    def getLangList(self):
        if self.langList:
            return self.langList

        language_dir = os.path.join(g_script_dir, 'languages')
        langlist = [self.default]

        if not os.path.isdir(language_dir):
            return langlist

        for file in os.listdir(language_dir):
            langfile = os.path.join(language_dir, file)
            if re.match('^[a-z0-9A-Z]+[_-]*[a-z0-9A-Z]+\.lang$', file) and os.path.isfile(langfile):
                langlist.append(re.sub('\.lang$', '', file))

        self.langList = list(set(langlist))
        self.langList.sort()
        return self.langList

    def rawtext(self, key):
        if key in self.package[self.lang]:
            return self.package[self.lang][key]
        else:
            return ''

    def loadDefaultLanguage(self):
        self.setTextToLangPackage(self.default, {
            'app_title': " Modules Manager (v{})",

            'unrecognized_option': "Unrecognized option '{}'",
            'unrecognized_command': "Unrecognized command '{}'",
            'file_or_folder_already_existing': "There is already an existing file or folder: '{}'",
            'link_no_exists_file': "Link to a file or directory that does not exist: '{}'",
            'existing_file_or_folder': "It's an existing file or folder: '{}'",
            'no_init': "This directory has not been initialized with modman",
            'output_msg_warning': '[Warning] {}',
            'output_msg_error': '[Error] {}',
            'init_warning_file_exists': "'{}' already exists, but it's a file. use the '--force' option "
                                        "to force create as a folder",
            'already_init': "This directory has already been initialized",
            'init_success': "Initialized successfully",
            'total_of_module': "Total of {} modules",
            'missing_clone_uri': "Missing the module clone uri",
            'clone_error_remove_dir': "(clone) There was an error been occurred when removing directory:\n {}",
            'missing_module_name': 'Missing a module name or wildcard',
            'missing_lang_code': 'Missing a language code',
            'module_update_confirm': "There are {} module(s) that will be updated, whether to continue?(y/n) ",
            'module_deploy_confirm': "There are {} module(s) that will be deployed, whether to continue?(y/n) ",
            'module_undeploy_confirm': "There are {} module(s) that will be undeployed, whether to continue?(y/n) ",
            'module_remove_confirm': "There are {} module(s) that will be removed, whether to continue?(y/n) ",
            'update_line': "\n-------- update '{}' --------",

            'deploying_prompt': "deploying '{}'",
            'applying_prompt': "- Applying {} '{}'\n    {} '{}'",
            'flag_ok': '[ok]',
            'flag_fail': '[fail]',
            'flag_copyfrom': 'COPY FROM',
            'flag_linkto': '=>',
            'deploying_subtotal': "Total: {},  New: {},  Warning: {}\n",
            'deploying_grand_total': "Total Item: {}, Total New: {}, Total Warning: {}\n",

            'undeploying_prompt': "undeploying '{}'",
            'undeploy_removing_prompt': "- remove {} '{}'",
            'undeploying_subtotal': "Total: {}, Warning: {}\n",
            'undeploying_grand_total': "Total: {}, Warning: {}\n",

            'clean_path_no_exists': "Path does not exists: '{}'",
            'clean_path_out_of_range': "The path is not in the current project directory: '{}'",
            'clean_remove_link': "- remove invalid link [ok] '{}'\n     links to '{}'",
            'clean_remove_empty_dir': "- remove empty directory [ok] '{}'",
            'clean_grand_total': "Total: {}, Warning: {}\n",

            'remove_prompt': "removing '{}'",

            'language_change': "The language has been switched to '{}'",
            'language_no_exists': "The language code '{}' does not exists",

            'version': "Module Manager Version: {}",
            'finish': 'Finish!',
        })

        self.setTextToLangPackage(
            self.default,
            'help',
            "\n"
            " usage: modman.bat <command> [<module>]... [<options> [<value>]...]...\n"
            " usage: py modman.py <command> [<module>]... [<options> [<value>]...]...\n"
            " ------------------------------------------------------------------------ \n"
            " <command>:\n\n"
            "  list             list all valid modules\n"
            "  l                same as 'list'\n"
            "  init             initialize the pwd as the modman deploy root\n"
            "  i                same as 'init'\n"
            "  clone            checkout a new modman-compatible module using git clone\n"
            "  c                same as 'clone'\n"
            "  update           update all modules that are currently checked out\n"
            "  up               same as 'update'\n"
            "  deploy           deploy an existing module\n"
            "  d                same as deploy\n"
            "  undeploy         remove an existing module without deleting the files\n"
            "  ud               same as undeploy\n"
            "  deploy-all       deploy all valid modules (like 'deploy *')\n"
            "  da               same as 'deploy-all'\n"
            "  d-all            same as 'deploy-all'\n"
            "  remove           remove a module (DELETES MODULE FILES)\n"
            "  rm               same as 'remove'\n"
            "  clean            clean up broken symlinks (run this after deleting a module)\n"
            "  help             display this help message\n"
            "  h                same as 'help'\n"
            "  -h               same as 'help'\n"
            "  --h              same as 'help'\n"
            "  -help            same as 'help'\n"
            "  --help           same as 'help'\n"
            "  version          display the modman script's version\n"
            "  v                same as 'version'\n"
            "  -v               same as 'version'\n"
            "  --v              same as 'version'\n"
            "  -version         same as 'version'\n"
            "  --version        same as 'version'\n"
            "  pjpath           show project path\n"
            "  mmpath           show modman path\n"
            "  lang             show current language\n"
            "  setlang          set language\n"
            "\n"
            " <option>:\n\n"
            "  --force          overwrite existing files, ignore untrusted cert warnings\n"
            "  -f               same as '--force'\n"
            "  --copy           deploy by copying files instead of symlinks\n"
            "  --absolute       use absolute path to create symbolic links\n"
            "  --abs            same as '--absolute'\n"
            "  --yes            Warnings are not displayed when commands are executed in multiple modules\n"
            "  -y               same as '--yes'\n"
            "  --nodeploy       do not deploy immediately after Cloning\n"
            "  -nd              same as '--undeploy'\n"
            "  --all            list all directory name\n"
            "  -a               same as '--all'\n"
            "  --short          only list the directory name\n"
            "  --list           do not remove file or directory, only show list while cleaning\n"
            "  -s               same as '--short'\n"
            "  --undeploy       undeploy module before removing\n"
            "  -ud              same as '--undeploy'\n"
            "  --emptydir       Delete empty directories while cleaning\n"
            "  -ed              same as '--emptydir'\n"
            "")
        #en_us

